package com.fatkun;
//int a;
//
//

/**
 * 在GAE上抓取网址
 * @author Fatkun
 * @site http://fatkun.com
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.servlet.http.*;

import java.util.List;
import java.util.Properties;

import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@SuppressWarnings("serial")
public class URLServlet extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain; charset=utf-8");
		resp.setCharacterEncoding("UTF-8");
		URL url = new URL(
				"http://jiage.me/PriceList/price.php?type=icbcyin&time=2011-11-07%2013:00:46&platform=");

		// 读取源码
		BufferedReader reader = new BufferedReader(new InputStreamReader(url
				.openStream(), "UTF-8"));
		String line;
		String subject = "";
		double fCurPrice = 0;
		StringBuffer sb = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			//int nsubstr = line.indexOf("买入价：");
			//if (-1 != nsubstr) {
			//		int nsubstr2 = line.indexOf("卖出价");
			//		subject = line.substring(nsubstr + 2, nsubstr2);
			//		subject = subject.trim();
			//		fCurPrice = Double.valueOf(subject);
			//}
			sb.append(line).append("\n");
		}
		reader.close();
		int n1 = sb.indexOf("买入价");
		int n2 = sb.indexOf("卖出价");
		fCurPrice = Double.valueOf(sb.substring(n1+4,n2-1));
		
		n1 = sb.indexOf("最高价");
		n2 = sb.indexOf("最低价");

		// 输出在网页上
		//resp.getWriter().println(sb.toString());
		// 发送邮件
		// if (fFlag) {
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		// String msgBody = "...";

		try {
			// read each person's info and compare,then send one by one
			PersistenceManager pm = PMF.get().getPersistenceManager();
			String query = "select from " + UserData.class.getName();
			List<UserData> userdatas = (List<UserData>) pm.newQuery(query)
					.execute();
			if (userdatas.isEmpty()) {
				// No one
			} else {
				Message msg = new MimeMessage(session);
				for (UserData u : userdatas) {
					//System.out.println(u.getbTriggered());
					if ((1 != u.getbTriggered()) && (fCurPrice >= u.getMax() || fCurPrice <= u.getMin())) {
						//System.out.println("debug:before email");
						msg.setFrom(new InternetAddress("liyun8552@gmail.com",
								"Admin"));
						msg.addRecipient(Message.RecipientType.TO,
								new InternetAddress(u.getUserEmail(),
										Double.toString(fCurPrice)));
						msg.setSubject(Double.toString(fCurPrice));
						msg.setText(sb.substring(n1,n2+8));
						Transport.send(msg);
						
						//UserData tmpu(u.getUserEmail(),u.getMax(),u.getMin(),1);
						//pm.deletePersistent(u);
						u.setbTriggered(1);
						//System.out.println(u.getbTriggered());
						pm.makePersistent(u);

					}
				}

			}
			pm.close();

		} catch (AddressException e) {
			// ...
		} catch (MessagingException e) {
			// ...
			// }
		}
	}
}
